package com.suxin.test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/14 18:14
 */
@Slf4j
public class EcoClient {

    public static void main(String[] args) throws Exception{
        EcoClient ecoClient = new EcoClient();
        ecoClient.start();
    }

    public void start() throws Exception{
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture channelFuture = bootstrap
                .group(bossGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(
                                        new DelimiterBasedFrameDecoder(
                                        1024,
                                        Unpooled.copiedBuffer(System.getProperty("line.separator"),
                                                Charset.defaultCharset()))
                                )
                                .addLast(new EcoClientHandler());
                    }
                })
                .connect(new InetSocketAddress("127.0.0.1",9999)).sync();
        log.info("client connect 完成! ");
        channelFuture.channel().closeFuture().sync();
        log.info("client connect close! ");
    }

}
